package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.utils.BtnUtils;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/5/29.
 */

public class NewCkActivity extends BaseActivity {
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll,tv_title,tv_num;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh ,lsbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType = "rdcck";
    private Logger log;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fpzzx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
        tv_title= (TextView) findViewById(R.id.ic_num).findViewById(R.id.tv_title);
        tv_num= (TextView) findViewById(R.id.ic_num).findViewById(R.id.tv_num);
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("周转箱出库");
        setSupportActionBar(toolbar);

        tv_title.setText("已扫数量:  0");
        tv_num.setText("待出库数量:  0");

        /**
         * 刷新框架
         * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager=new DBManager(mContext);
        ls_bh= new ArrayList<>();
        ls_xzbh= new ArrayList<>();
        lsbh= new ArrayList<>();
        setData();

//        SelectBYTask selectBYTask = new SelectBYTask();
//        selectBYTask.execute();
        SelectNum();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
        btn_sure.setEnabled(true);

    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    if(BtnUtils.isFastClick()){
                        senddata();
                    }
                    break;
                case R.id.btn_delete:
                    if(BtnUtils.isFastClick()){
                        deleteZzxbh();
                    }
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                ZZXFPAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        if(code.contains("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else {
            isScan(code);
        }
        return code;
    };

    /**
     * 判断是否已扫
     * */
    private void isScan(String bh){
        Boolean isExist = dbManager.IsExistZzxbh(bh,dataType, MyApplication.getUserInfo().getDid());
        if(isExist){
            T.showShort(mContext,"该二维码已扫描");
        }else{
            dbManager.addZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
            setData();
        }
    }

    /**
     * 列表赋值
     * */
    private void setData(){
        ls_bh.clear();
        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        tv_title.setText("已扫数量:"+lsbh.size());
        if(lsbh==null){
            return;
        }else {
            ls_bh.addAll(lsbh);
        }
        if(ls_bh==null){
            return;
        }
        zzxfpAdapter = new ZZXFPAdapter(ls_bh);
        mRecyclerView.setAdapter(zzxfpAdapter);

        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener()

        {
            @Override
            public void onItemClick(int position) {
                if(ZZXFPAdapter.getIsSelected().get(position)==true){
                    ZZXFPAdapter.getIsSelected().put(position, false);
                    zzxfpAdapter.notifyDataSetChanged();
                }else{
                    ZZXFPAdapter.getIsSelected().put(position, true);
                    zzxfpAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });


    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的编号!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
            dbManager.deleteFPZzxbh(ls_bh,dataType,MyApplication.getUserInfo().getDid());
            setData();
        });
        builder.setNegativeButton("取消", (dialog, which) -> {

        });
        builder.show();
    }

    /**
     * 上传数据
     * */
    private void senddata(){

        lsbh.clear();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要分配的编号!");
        }else {
            btn_sure.setClickable(false);
            showSendInfo(lsbh);
        }
    }

    /**
     * 上传数据是的提示框
     * */
    private void showSendInfo(final List<String> ls_bh){
        btn_sure.setClickable(true);
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要出库这"+ls_bh.size()+"个周转箱吗?");
        builder.setPositiveButton("确定", (dialog, which) -> {
            ls_xzbh.clear();
            ls_xzbh.addAll(ls_bh);

            btn_sure.setClickable(true);

            Map<String, Object> map = new HashMap<>();
            map.put("userId", MyApplication.getUserInfo().getId());
            map.put("did", MyApplication.getUserInfo().getDid());
            map.put("tboxsNo",ls_xzbh);
            String json = JsonUtil.toJson(map);

            SendTask sendTask = new SendTask();
            sendTask.execute(json);
//            outTbox(json);

        });
        builder.setNegativeButton("取消", (dialog, which) -> {
            btn_sure.setClickable(true);
        });
        builder.show();
    }

    /**
     * 上传的数据请求
     * */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(false);
            btn_sure.setClickable(true);
        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pdaOut.do", "tboxsOut"),"json="+params[0]);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            btn_sure.setClickable(true);

            try {
                if (result == null || result.length() == 0) {
                    showAlertDialog("连接异常");
                    return;
                }
                if(result.contains("state")){
                    TboxsOutInfo tboxsOutInfo = JsonUtil.getPerson(result, TboxsOutInfo.class);
                    String state = tboxsOutInfo.getState();
                    String successNum = tboxsOutInfo.getSuccessNum();

                    if(state.equals("0")){
                        dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                        setData();
                        showAlertDialog("成功出库周转箱"+successNum+"个");
                    }else if(state.equals("2")){
                        showAlertDialog("操作失败,请重新操作或进行运维申请");
                    }else if(state.equals("3")){
                        showAlertDialog("参数异常");
                    }else if(state.equals("1")){
                        String ycTboxsMsg="",unbdTboxsMsg="",unSupplierTboxsMsg=""
                                ,succMsg="";
                       if(result.contains("ycTboxs")){
                          List<String> ls_ycTboxs=tboxsOutInfo.getYcTboxs();
                          String ycTboxs = JsonUtil.toJson(ls_ycTboxs);
                          ycTboxsMsg = "周转箱"+ycTboxs+"不符合出库条件,请检查状态";
                           ls_xzbh.removeAll(ls_ycTboxs);
                       }
                        if(result.contains("unbdTboxs")){
                            List<String> ls_unbdTboxs=tboxsOutInfo.getUnbdTboxs();
                            String unbdTboxs = JsonUtil.toJson(ls_unbdTboxs);
                            unbdTboxsMsg = "周转箱"+unbdTboxs+"未绑定";
                            ls_xzbh.removeAll(ls_unbdTboxs);
                        }
                        if(result.contains("unSupplierTboxs")){
                            List<String> ls_unSupplierTboxs=tboxsOutInfo.getUnSupplierTboxs();
                            String unSupplierTboxs = JsonUtil.toJson(ls_unSupplierTboxs);
                            unSupplierTboxsMsg = "周转箱"+unSupplierTboxs+"未绑定运输供应商";
                            ls_xzbh.removeAll(ls_unSupplierTboxs);
                        }
                        if(!successNum.equals("0")){
                            succMsg="成功出库"+successNum+"个周转箱";
                        }
                        dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                        setData();
                        String Msg = succMsg+ycTboxsMsg+unbdTboxsMsg+unSupplierTboxsMsg;
                        showAlertDialog(Msg);
                    }

                }else{
                    showAlertDialog(result);
                }

            }catch (Exception e) {
                log.info("tboxsOut:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    private void outTbox(String json){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(false);
        btn_sure.setClickable(true);

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        client.newBuilder().connectTimeout(5*60, TimeUnit.SECONDS);
        client.newBuilder().readTimeout(5*60,TimeUnit.SECONDS);
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("json",json);//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(UrlUtils.getInstance().getNewJavaUrl("pdaOut.do",
                        "tboxsOut"))
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(()->{
                    showAlertDialog("连接异常");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                final String result = response.body().string();

                runOnUiThread(()->{
                    try{
                    if(result.contains("state")){
                        TboxsOutInfo tboxsOutInfo = JsonUtil.getPerson(result, TboxsOutInfo.class);
                        String state = tboxsOutInfo.getState();
                        String successNum = tboxsOutInfo.getSuccessNum();

                        if(state.equals("0")){
                            dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                            setData();
                            showAlertDialog("成功出库周转箱"+successNum+"个");
                            SelectNum();
                        }else if(state.equals("2")){
                            showAlertDialog("操作失败,请重新操作或进行运维申请");
                        }else if(state.equals("3")){
                            showAlertDialog("参数异常");
                        }else if(state.equals("1")){
                            String ycTboxsMsg="",unbdTboxsMsg="",unSupplierTboxsMsg=""
                                    ,succMsg="";
                            if(result.contains("ycTboxs")){
                                List<String> ls_ycTboxs=tboxsOutInfo.getYcTboxs();
                                String ycTboxs = JsonUtil.toJson(ls_ycTboxs);
                                ycTboxsMsg = "周转箱"+ycTboxs+"不符合出库条件,请检查状态";
                                ls_xzbh.removeAll(ls_ycTboxs);
                            }
                            if(result.contains("unbdTboxs")){
                                List<String> ls_unbdTboxs=tboxsOutInfo.getUnbdTboxs();
                                String unbdTboxs = JsonUtil.toJson(ls_unbdTboxs);
                                unbdTboxsMsg = "周转箱"+unbdTboxs+"未绑定";
                                ls_xzbh.removeAll(ls_unbdTboxs);
                            }
                            if(result.contains("unSupplierTboxs")){
                                List<String> ls_unSupplierTboxs=tboxsOutInfo.getUnSupplierTboxs();
                                String unSupplierTboxs = JsonUtil.toJson(ls_unSupplierTboxs);
                                unSupplierTboxsMsg = "周转箱"+unSupplierTboxs+"未绑定运输供应商";
                                ls_xzbh.removeAll(ls_unSupplierTboxs);
                            }
                            if(!successNum.equals("0")){
                                succMsg="成功出库"+successNum+"个周转箱";
                                SelectNum();
                            }
                            dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                            setData();
                            String Msg = succMsg+ycTboxsMsg+unbdTboxsMsg+unSupplierTboxsMsg;
                            showAlertDialog(Msg);
                        }
                    }else{
                        showAlertDialog(result);
                    }
                    } catch (Exception e) {
                        log.info("outTbox:"+e.toString()+"/result="+result);
                        e.printStackTrace();
                        showAlertDialog(e.toString());
                    }
                });
            }
        });
    }

    /**
     * 查询待出库数量的数据请求
     * */

    public class SelectBYTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(false);
            btn_sure.setClickable(true);
        }

        protected String doInBackground(String... params) {
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpp.do",
                    "SelectBY"),"did="+MyApplication.getUserInfo().getDid());
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            btn_sure.setClickable(true);

            try {
                if (result == null || result.length() == 0) {
                    showAlertDialog("连接异常，未查询出待出库数量");
                    return;
                }
                if(result.contains("count")){
                    String count = JsonUtil.getMsg(result,"count").toString();
                    tv_num.setText("待出库数量:  "+count);
                }else{
                    showAlertDialog(result);
                }

            }catch (Exception e) {
                log.info("SelectBY:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    private void SelectNum(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(false);
        btn_sure.setClickable(true);

        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("did",String.valueOf(MyApplication.getUserInfo().getDid()));//传递键值对参数
        Request request = new Request.Builder()//创建Request 对象。
                .url(UrlUtils.getInstance().getNewJavaUrl("rdcpp.do",
                        "SelectBY"))
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(()->{
                    showAlertDialog("连接异常,未查询出待出库数量");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                final String result = response.body().string();

                runOnUiThread(()->{
                    try {
                        if(result.contains("count")){
                            String count = JsonUtil.getMsg(result,"count").toString();
                            tv_num.setText("待出库数量:  "+count);
                        }else{
                            showAlertDialog(result);
                        }
                    } catch (Exception e) {
                    log.info("SelectNum:"+e.toString()+"/result="+result);
                    e.printStackTrace();
                    showAlertDialog(e.toString());
                }
                });
            }
        });
    }

    /**绑定返回值*/
    public class TboxsOutInfo{
        private String successNum;
        private List<String> ycTboxs;
        private List<String> unbdTboxs;
        private List<String> unSupplierTboxs;
        private String state;

        public String getSuccessNum() {
            return successNum;
        }

        public List<String> getYcTboxs() {
            return ycTboxs;
        }

        public List<String> getUnbdTboxs() {
            return unbdTboxs;
        }

        public List<String> getUnSupplierTboxs() {
            return unSupplierTboxs;
        }

        public String getState() {
            return state;
        }
    }

}
